# rank_service.py
import grpc

import rank_pb2
import rank_pb2_grpc
from concurrent import futures


class RankService(rank_pb2_grpc.RankServiceServicer):
    def __init__(self):
        self.players = []

    def AddPlayer(self, request, context):
        self.players.append(request)
        self.players.sort(key=lambda x: x.score, reverse=True)
        return request

    def GetPlayerRank(self, request, context):
        player_names = [player.name for player in self.players]
        if request.player_name in player_names:
            rank = player_names.index(request.player_name) + 1
            return rank_pb2.GetPlayerRankResponse(rank=rank)
        else:
            context.set_code(grpc.StatusCode.NOT_FOUND)
            context.set_details('Player not found')
            return rank_pb2.GetPlayerRankResponse(rank=-1)

    def ListTopPlayers(self, request, context):
        return self.players[:request.count]


def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    rank_pb2_grpc.add_RankServiceServicer_to_server(RankService(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    server.wait_for_termination()


if __name__ == '__main__':
    serve()
